/**
 * @project: parallel-task
 * @package: com.ngplat.paralleltask.task
 * @filename: TaskProcessor.java
 *
 * Copyright (c) 2018 eSunny Info. Tech Ltd. All rights reserved.
 * 
 */
package com.ngplat.paralleltask.task;

import com.ngplat.paralleltask.exception.TaskExecutionException;
import com.ngplat.paralleltask.model.TaskInfo;

/**
 * @typename: TaskProcessor
 * @brief: 任务处理器 - 业务逻辑真正执行的地方
 * @author: KI ZCQ
 * @date: 2018年5月24日 上午8:57:33
 * @version: 1.0.0
 * @since
 * 
 */
public abstract class TaskProcessor implements Taskable, TaskParallelExePool {

	// serialVersionUID
	private static final long serialVersionUID = 2244445440454580331L;
	
	// 上下文
	protected TaskContext context;
	
	// 任务基本信息
	protected TaskInfo taskInfo;

	/**
	 * Empty constructor for TaskProcessor initialization.
	 */
	public TaskProcessor() {
		// Initialize the TaskContext
		if(context == null) {
			context = TaskContext.newContext();
		}
	}

	/**
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		try {
			// 执行前预加工, 参数构造等
			beforeExecute(context);
			// 执行真正的业务处理逻辑
			runWorker(context);
			// 处理后的收尾
			afterExecute(context);
		} catch (Exception e) {
			context.putException(taskInfo.getTaskId(), e);
			throw e;
		}
	}

	/**
	 * @Description: 真正执行业务逻辑的地方
	 * @param context
	 * @throws TaskExecutionException
	 */
	@Override
	public abstract void runWorker(TaskContext context) throws TaskExecutionException;

	/**
	 * @Description: 开始执行前的处理
	 * @param context
	 */
	@Override
	public void beforeExecute(TaskContext context) {
		// Empty Method, allow to write override
	}

	/**
	 * @Description: 任务执行后的处理
	 * @param context
	 */
	@Override
	public void afterExecute(TaskContext context) {
		// Empty Method, allow to write override
	}

	/**    
	 * @Description: 初始化
	 * @param taskInfo
	 */
	public void initialize(TaskInfo taskInfo) {
		this.taskInfo = taskInfo;
	}

	/**
	 * context
	 *
	 * @return  the context
	 * @since   1.0.0
	*/
	public TaskContext getContext() {
		return context;
	}

}
